import {createRouter, createWebHashHistory} from 'vue-router'
import Home from '@/views/Home/Home.vue'
import useStore from '@/store'
import Message from '@/components/XtxMessage'
const router =  createRouter({
  scrollBehavior: () => {
    return { top: 0 }
  },
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      component: () => import('@/views/Layout/Layout.vue'),
      children: [
        {
          path: '',
          component: Home
        },
        {
          // 动态路由
          path: 'category/:id',
          component: () => import('@/views/Category/Category.vue')
        },
        {
          // 详情页
          path: 'product/:id',
          component: () => import('@/views/Goods/Goods.vue')
        },
        {
          // 购物车
          path: 'cart',
          component: () => import('@/views/Cart/Cart.vue')
        },
        {
          // 结算
          path: 'member/checkout',
          component: () => import('@/views/Member/Pay/Checkout.vue')
        },
        {
          path: '/member/pay',
          component: () => import('@/views/Member/Pay.vue')
        },
        {
          path: '/pay/callback',
          component: () => import('@/views/Member/Pay/Callback.vue')
        }
      ]
    },
    {
      path: '/login',
      component: () => import('@/views/Login/Login.vue')
    },
    {
      path: '/login/callback',
      component: () => import('@/views/Login/Callback.vue')
    },
    {
      path: '/play',
      component: () => import('@/views/Playground.vue')
    }
  ]
})

router.beforeEach((to, from, next) => {
  const {cart} = useStore()
  if(cart.isLogin === false && to.path === '/member/checkout'){
    Message.warning('请先登录')
    const url = '/login?redirect=' + to.fullPath
    next(url)
  } else {
    next()
  }
})

export default router